package com.blindnews.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.blindnews.mapper.NewsMapper;
import com.blindnews.pojo.Channel;
import com.blindnews.pojo.News;
import com.blindnews.service.NewsService;
import com.blindnews.utils.NewsContent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class NewServiceA implements NewsService {

    @Autowired
    private NewsMapper newsMapper;
    @Autowired
    private NewsContent newsContent;


    @Override
    public List<News> getNewsList(String channelId) {
        List<News> newsList = newsMapper.getNewsList(channelId);
        return newsList;
    }

    @Override
    public List<Channel> getChannel() {
        List<Channel> channel = newsMapper.getChannel();
        return channel;
    }

    @Override
    public News upLoadNews(String id) {
        News news =newsMapper.upLoadNews(id);
        return news;
    }


    @Override
    public Boolean downloadnews(ResponseEntity<String> response) throws IOException {
        //从Controller获得的返回的response
//        根据response.getStatusCode()判断
        if (response.getStatusCode() == HttpStatus.OK) {
            System.out.println("Request Successful.");
            System.out.println(response.getBody());
            //解析返回的复杂JSON数据
            JSONObject jsTemp = JSONObject.parseObject(response.getBody());
            JSONObject jsonObject = jsTemp.getJSONObject("showapi_res_body");
            JSONObject jsonObject1 = jsonObject.getJSONObject("pagebean");
            int JSON_allnum = jsonObject1.getIntValue("allNum");
            int JSON_maxResult = jsonObject1.getIntValue("maxResult");
            int JSON_currentPage = jsonObject1.getIntValue("currentPage");
            int JSON_allPages = jsonObject1.getIntValue("allPages");
            System.out.println(JSON_allnum);
            System.out.println(JSON_maxResult);
            System.out.println(JSON_currentPage);
            System.out.println(JSON_allPages);
//            解析新闻数据
            JSONArray contentlist = jsonObject1.getJSONArray("contentlist");

            System.out.println(contentlist);
            JSONObject content;
//            将解析Json后的新闻数据放入News实体类数组中
            List<News> newsList = new ArrayList<>();
            for (int i = 0; i < JSON_maxResult; i++) {
                content = contentlist.getJSONObject(i);
                News item = new News();
                item.setChannelId(content.get("channelId").toString());
                item.setLink(content.get("link").toString());
                item.setId(content.get("id").toString());
                item.setSource(content.get("source").toString());
                item.setTitle(content.get("title").toString());
                item.setPubDate(content.get("pubDate").toString());
                item.setChannelName(content.get("channelName").toString());
                item.setDr("0");//置dr为0，表示尚未获取正文
                newsList.add(item);
                System.out.println(item);
            }
//            使用爬虫获取新闻正文，加到List中
            List<News> newsList1 = newsContent.getContent(newsList);
//            调用Mapper层，将数据下载到数据库中
            newsMapper.addnews(newsList1);
            return true;

        }else {
            System.out.println("Request Failed");
            System.out.println(response.getStatusCode());
            return false;
        }
    }

    @Override
    public Boolean downloadchannel(ResponseEntity<String> response) {
        //从Controller获得的返回的response
//        根据response.getStatusCode()判断
        if (response.getStatusCode() == HttpStatus.OK) {
            System.out.println("Request Successful.");
            System.out.println(response.getBody());
            //解析返回的复杂JSON数据
            JSONObject jsTemp = JSONObject.parseObject(response.getBody());
            JSONObject jsonObject = jsTemp.getJSONObject("showapi_res_body");
            JSONArray channelList=jsonObject.getJSONArray("channelList");

            int JSON_totalNum = jsonObject.getIntValue("totalNum");
            System.out.println(JSON_totalNum);
//            解析新闻数据
            System.out.println(channelList);
            JSONObject content;
//            将解析的新闻数据放入News实体类数组中
            List<Channel> channels = new ArrayList<>();
            for (int i = 0; i < JSON_totalNum; i++) {
                content = channelList.getJSONObject(i);
                Channel item = new Channel();
                item.setChannelId(content.get("channelId").toString());
                item.setName(content.get("name").toString());
                channels.add(item);
                System.out.println(item);
            }
//            调用Mapper层，将数据下载到数据库中
            newsMapper.addchannel(channels);
            return true;

        }else {
            System.out.println("Request Failed");
            System.out.println(response.getStatusCode());
            return false;
        }
    }

//    @Override
//    public void addChannel(List<Channel> channelList) {
//        newsMapper.addchannel(channelList);
//        System.out.println("服务层");
//    }
//    @Override
//    public void addNewsList(List<News> newsList) {
//        newsMapper.addnews(newsList);
//        System.out.println("服务层");
//    }



//    @Override
//    public void getNewsInfo(String url) {
//        // 设置请求头
//        int count=0;
//        // 设置请求头
//        String userAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36";
//        try {
//            // 获取详情页数据
//            Document detailDoc = Jsoup.connect(url).header("User-Agent", userAgent).get();
//            System.out.println(detailDoc.text());
//            // 获取新闻详情,select获取Post_body的所有子标签；
//            Elements newsTitle = detailDoc.select("div.post_main>h1");//获得标题
//            System.out.println("Title："+newsTitle.text());
//            Elements newsContent = detailDoc.select("div.post_body>*");//获得正文
//
//            String[] newsListArr = newsContent.text().split(" ");
//            System.out.println("Conten："+newsListArr.length+"行");
//            StringBuilder stringBuilder = new StringBuilder();
//            String content=null;
//            for (String news : newsListArr) {
//                count+=1;
//
////                将空内容标签过滤掉
//                if(news.isEmpty()){
//                    continue;
//                }
////                遇到延伸阅读，不再获取，跳出循环
//                if(news.equals("延伸阅读"))
//                {
//                    break;
//                }
//                System.out.println("第"+count+"段");
//                System.out.println(news);
//                stringBuilder.append(news);
//            }
//            content=stringBuilder.toString();
//            System.out.println(content);
//            newsMapper.addNewsInfo(content);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }


}
